package com.nsgf.library.ui.page;

import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED;
import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_DRAGGING;
import static com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_HIDDEN;
import static com.nsgf.library.utils.Utils.isAvilible;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.ClockInBean;
import com.nsgf.library.data.bean.ProjectBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityReservoirDetailsBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.utils.ToastUtils;

/**
 * 单水库详情
 */
public class ReservoirDetailsActivity extends BaseActivity {

    StateHolder mState;

    private AccountRequester mAccountRequester;
    ClockInBean.DataBean.LateAndEarlyListBean info;

    @Override
    protected void initViewModel() {
        mState = getActivityScopeViewModel(StateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_reservoir_details, BR.vm, mState)
                .addBindingParam(BR.click, new ClickProxy());
    }


    BottomSheetBehavior mBehavior;

    private ActivityReservoirDetailsBinding mBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getLifecycle().addObserver(mAccountRequester);
        mBinding = (ActivityReservoirDetailsBinding) getBinding();

        mBehavior = BottomSheetBehavior.from(mBinding.bottomSheet);
        mBehavior.setState(STATE_COLLAPSED);
        mState.projectInfo.set((ClockInBean.DataBean.LateAndEarlyListBean) getIntent().getSerializableExtra("info"));


        mBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {

                if (newState == STATE_HIDDEN) {
                    mBehavior.setState(STATE_COLLAPSED);
                    mBinding.ivNsgfHomeSheet.setImageResource(R.drawable.ic_nsgf_home_sheet_up);
                } else if (newState == STATE_COLLAPSED) {
                    mBinding.ivNsgfHomeSheet.setImageResource(R.drawable.ic_nsgf_home_sheet_up);
                } else {
                    if (newState != STATE_DRAGGING)
                        mBinding.ivNsgfHomeSheet.setImageResource(R.drawable.ic_nsgf_home_sheet_down);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });


        String url = "file:///android_asset/roadLine/index.html";
        WebSettings mWebSettings = mBinding.webView.getWebView().getSettings();
        mWebSettings.setJavaScriptEnabled(true);//设置支持javaScript
        mBinding.webView.loadUrl(url);
        // 当页面加载完成后调用JavaScript方法
        mBinding.webView.getWebView().setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("lon", mState.projectInfo.get().getLon());
                jsonObject.addProperty("lat", mState.projectInfo.get().getLat());
                callJavaScriptZoomToPointFunction(jsonObject);
            }
        });


        mAccountRequester.getPictureDetails(mState.projectInfo.get().getProjectCode());

        mAccountRequester.getReservoirResult().observe(this, new Observer<ResponseStatus<ProjectBean>>() {
            @Override
            public void onChanged(ResponseStatus<ProjectBean> dataBeanResponseStatus) {

                if (dataBeanResponseStatus.getResponseCode() == 200) {
                    mState.projectBeanState.set(dataBeanResponseStatus.getData());
                } else {
                    showToast(dataBeanResponseStatus.getMsg());
                }
            }
        });

    }


    /**
     * gis绘制地图中心点
     *
     * @param object
     */
    private void callJavaScriptZoomToPointFunction(JsonObject object) {
        JsonArray array = new JsonArray();
        object.addProperty("status", "66");
        array.add(object);
        mBinding.webView.getWebView().evaluateJavascript("zoomToPointProject(" + object + "," + "'" + array + "'" + ");", null);
    }

    public class ClickProxy {

        public void navigation() {
            showMap(ReservoirDetailsActivity.this,
                    mState.projectInfo.get().getLon(),
                    mState.projectInfo.get().getLat(),
                    mState.projectInfo.get().getFacilityName());
        }
    }


    public static Dialog dialog;

    /**
     * 选择地图导航
     *
     * @param context
     * @param longitude
     * @param latitude
     * @param pondName
     */
    public static void showMap(Context context, String longitude, String latitude, String pondName) {
        try {

            dialog = new Dialog(context, R.style.dialogstyle);
            View view = View.inflate(context, R.layout.dialog_map_navigation, null);
            TextView tv_map_gd = view.findViewById(R.id.tv_map_gd);
            TextView tv_map_bd = view.findViewById(R.id.tv_map_bd);
            TextView tv_dialog_map_navigation_close = view.findViewById(R.id.tv_dialog_map_navigation_close);
            tv_dialog_map_navigation_close.setOnClickListener(v -> dialog.dismiss());
            tv_map_bd.setOnClickListener(v -> {


                if (isAvilible(context, "com.baidu.BaiduMap")) {//传入指定应用包名
                    ToastUtils.showShortToast("即将用百度地图打开导航");
                    Intent i1 = new Intent();
                    i1.setData(Uri.parse("baidumap://map/geocoder?location=" + latitude + "," + longitude + "&coord_type=wgs84&src=andr.baidu.openAPIdemo"));
                    context.startActivity(i1);
                    dialog.dismiss();
                } else {
                    ToastUtils.showShortToast("没有安装百度地图客户端");
                }

            });
            tv_map_gd.setOnClickListener(v -> {
                //  com.autonavi.minimap这是高德地图的包名
                if (isAvilible(context, "com.autonavi.minimap")) {//传入指定应用包名
                    ToastUtils.showShortToast("即将用高德地图打开导航");
                    Intent intent = new Intent("android.intent.action.VIEW", Uri.parse("androidamap://navi?sourceApplication=区域矩阵APP&lat=" + "&dev=1"));
                    intent.setPackage("com.autonavi.minimap");
                    intent.setData(Uri.parse("androidamap://viewMap?sourceApplication=区域矩阵APP&poiname=" + pondName + "&lat=" + latitude + "&lon=" + longitude + "&dev=1"));
                    context.startActivity(intent);
                    dialog.dismiss();
                } else {
                    ToastUtils.showShortToast("没有安装高德地图客户端");
                    return;
                }
                dialog.dismiss();
            });
            dialog.setContentView(view);

            dialog.show();
            Window window = dialog.getWindow();
            window.setGravity(Gravity.BOTTOM);
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
            window.setAttributes(layoutParams);
        } catch (Exception e) {
            e.getMessage();
        }
    }


}
